package linked;

//约瑟夫问题 单向环形链表
public class Josepfu {
    public static void main(String[] args) {
        CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
        circleSingleLinkedList.addBoy(5);
        circleSingleLinkedList.showBoy();
        circleSingleLinkedList.countBoy(1, 2, 5);
    }
}


//创建环形的单向链表
class CircleSingleLinkedList {
    //创建一个first节点
    private Boy first = null;

    //添加小孩构建环形的链表
    public void addBoy(int nums) {
        if (nums < 1) {
            System.out.println("值不正确");
            return;
        }
        Boy curBoy = null; //辅助指针
        //使用for来创建环形链表
        for (int i = 1; i <= nums; i++) {
            //根据编号创建节点
            Boy boy = new Boy(i);
            //第一个小孩
            if (i == 1) {
                first = boy;
                first.setNext(first);//构成环装
                curBoy = first;
            } else {
                curBoy.setNext(boy);
                boy.setNext(first);
                curBoy = boy;
            }
        }
    }

    public void countBoy(int startNo, int countNo, int nums) {
        //先对数据进行校验
        if (first == null || startNo < 1 || startNo > nums) {
            System.out.println("参数有误请重新输入");
            return;
        }
        //创建一个辅助指针 帮助小孩出圈
        Boy helper = first;
        while (true) {
            if (helper.getNext() == first) { //说明helper指向最后的小孩节点
                break;
            }
            helper = helper.getNext();
        }
        //小孩报数先让first和helper移动k-1次
        for (int i = 0; i < startNo - 1; i++) {
            first = first.getNext();
            helper = helper.getNext();
        }
        while (true) {
            if (helper == first) {
                break; //说明圈中只有一个小孩
            }
            for (int i = 0; i < countNo - 1; i++) {
                first = first.getNext();
                helper = helper.getNext();
            }
            //这时first指向的节点就是要出圈的节点
            System.out.printf("小孩出圈%d", first.getNo());
            first = first.getNext();
            helper.setNext(first);
        }
        System.out.printf("最后在圈的小孩是%d",first.getNo());
    }



    //遍历当前环形链表
    public void showBoy() {
        if (first == null) {
            System.out.println("没有任何小孩");
            return;
        }
        Boy curBoy = first;
        while (true) {
            System.out.printf("小孩的编号%d\n", curBoy.getNo());
            if (curBoy.getNext() == first) {//遍历完毕
                break;
            }
            curBoy = curBoy.getNext();
        }


    }

}

class Boy { //表示节点
    private int no;
    private Boy next;   //指向下一个节点，默认null

    public Boy(int no) {
        this.no = no;
    }

    public int getNo() {
        return no;
    }

    public Boy getNext() {
        return next;
    }

    public void setNext(Boy next) {
        this.next = next;
    }
}